<template>
  <op-dialog
    v-model="dialogVisibleRef"
    :title="title"
    @close="buttonClick('cancel')"
    @confirm="buttonClick('confirm')"
    width="800px"
    height="220px"
  >
    <div class="data-entry-box">
      <el-row v-if="getIndex('choose') > 0" class="labelBox">
        <el-col :span="9">
          <label>{{ getIndex('choose') }}.Choose upload method</label>
        </el-col>
        <el-col :span="15">
          <el-radio-group v-model="uploadMethod" class="ml-4" @change="uploadMethodChange">
            <el-radio label="1" size="large">Overwrite original data</el-radio>
            <el-radio label="2" size="large">New data</el-radio>
          </el-radio-group>
        </el-col>
      </el-row>
      <el-row v-if="getIndex('template') > 0" class="labelBox">
        <el-col :span="9">
          <label>{{ getIndex('template') }}.Download the original template file</label>
        </el-col>
        <el-col :span="15">
          <u @click="handleDownloadTemplate">{{ `${templateFileName}.xlsx` }}</u>
        </el-col>
      </el-row>
      <el-row v-if="getIndex('upload') > 0" class="labelBox data-entry-upload">
        <el-col :span="9">
          <label>{{ getIndex('upload') }}.Upload file</label>
        </el-col>
        <el-col :span="15">
          <op-upload-button
            :notice="fileNotice"
            :accept="fileAccept"
            :maxSize="100"
            :limit="1"
            iconName="IconExcel"
            v-model="fileList"
            @formChange="formChange"
          />
        </el-col>
      </el-row>
    </div>
  </op-dialog>
  <op-dialog-failed ref="failedRef" />
</template>

<script setup>
import { apiMethods } from '@/utils/http.js';
import { ElMessage, ElLoading } from 'element-plus';

const emits = defineEmits(['uploadSuccess']);

let dialogVisibleRef = ref(false);
let rowData = ref({});
let title = ref('');
let uploadMethod = ref('1');
// 导入接口
let excelImportUrl = ref('');
// 导入接口其他参数
let excelImportParams = ref({});
// 模板接口其他参数
let templateParams = ref({});
// 模板下载地址
let templateUrl = ref('');
// 模板标题文件下载名字
let templateFileName = ref('');

let fileList = ref([]);
let failedRef = ref(null);
let fileNotice = ref('');
let fileAccept = ref('');
let boxLabelList = ref([]);
// const _fileList = toRaw(fileList);

const uploadErrorFn = errData => {
  if (errData) failedRef.value.init({ downloadUrl: errData });
};

const buttonClick = async prop => {
  if (prop === 'cancel') {
    fileList.value = [];
    dialogVisibleRef.value = false;
  } else {
    if (!fileList.value?.length) {
      ElMessage.warning('Upload file is required');
      return;
    }
    const loading = ElLoading.service({
      lock: true,
      text: 'Loading',
    });
    let res = await apiMethods['post'](
      excelImportUrl.value,
      {
        multipartFile: fileList.value[0],
        downloadType: uploadMethod.value,
        ...excelImportParams.value,
      },
      true
    );
    loading.close();
    let code = res.data.code || res.data.errorCode;
    if (code == '200') {
      ElMessage({ message: 'Upload successful', type: 'success' });
      emits('uploadSuccess');
      dialogVisibleRef.value = false;
    } else if (code == '203') {
      uploadErrorFn(res.data.data);
    } else {
      ElMessage({ message: res.data.errorMsg || res.data.msg, type: 'error' });
    }
  }
};

const init = row => {
  dialogVisibleRef.value = true;
  rowData.value = row;
  // 弹窗标题
  title.value = row?.title || 'Excel Import';
  // 模版导出api
  templateUrl.value = row?.templateUrl;
  // 模版导出参数
  templateParams.value = row?.templateParams;
  // 模版文件名
  templateFileName.value = row?.templateFileName;
  // 导入api
  excelImportUrl.value = row?.excelImportUrl;
  // 导入参数
  excelImportParams.value = row?.excelImportParams;
  // 格式提示语
  fileNotice.value = row?.fileNotice || 'No more than 100M, Format: .xlsx';
  // 格式限制
  fileAccept.value = row?.fileAccept || '.xlsx';
  // 页面展示内容
  boxLabelList.value = row?.boxLabelList || ['template', 'upload'];
};

function uploadMethodChange() {
  init(rowData.value);
}
const destroy = row => {
  dialogVisibleRef.value = false;
};
const handleDownloadTemplate = () => {
  if (!templateUrl.value) return;
  apiMethods['post_export'](templateUrl.value, {
    fileName: templateFileName.value,
    downloadType: uploadMethod.value,
    ...templateParams.value,
  });
};
const formChange = data => {
  // fileList.value = data;
};

const getIndex = val => {
  return boxLabelList.value.indexOf(val) + 1;
};
defineExpose({ init, destroy });
</script>

<style lang="scss" scoped>
.data-entry-box {
  margin: 10px 0;
  .labelBox {
    display: flex;
    align-items: center;
    height: 40px;

    label {
      font-weight: 500;
      color: #303133;
    }
    u {
      text-decoration: none;

      font-weight: 500;
      color: var(--el-color-primary);
      line-height: 20px;
      cursor: pointer;
    }
  }
  .data-entry-upload {
    align-items: start;
    margin-top: 10px;
  }
}
</style>

<style>
.el-message {
  z-index: 6666 !important;
}
</style>
